import gzip
import scipy
import sparsesvd
import matplotlib.pyplot as plt

# 从.gz压缩包读取数据到numpy矩阵
file = open("../data/Slashdot0811.txt", "r")
row = []
col = []
data = []
lines = file.readlines()
for line in lines:
    d = line.strip().split("\t")
    row.append(int(d[0]))
    col.append(int(d[1]))
    data.append(1)
m = max(row) + 1 #行数
n = max(col) + 1 #列数
coo_mat = scipy.sparse.coo_matrix((data, (row,col)), shape=(m, n))
csc_mat = coo_mat.tocsc()
print("数据读取完成.")


#svd分解
k = 10
ut, s, vt = sparsesvd.sparsesvd(csc_mat, k)
u = ut.T
print("svd分解完成.")

# 画散点图
plt.figure(figsize=(7,16))
for i in range(k-1):
    plt.subplot(9, 2, i + 1)
    plt.title("u{}-u{}".format(i+1, i+2))
    plt.xlabel("u{}".format(i+1))
    plt.ylabel("u{}".format(i+2))
    plt.plot(u[:,i], u[:,i+1])
for i in range(k-1):
    plt.subplot(9, 2, 10 + i)
    plt.title("v{}-v{}".format(i + 1, i + 2))
    plt.xlabel("v{}".format(i + 1))
    plt.ylabel("v{}".format(i + 2))
    plt.plot(vt[i], vt[i + 1])
plt.tight_layout()
plt.savefig("question2.png")



